//index.js
//获取应用实例
const app = getApp()
var defaultColor = "#808080";
var color = "#A01C2C";
var QQMapWX = require('../addAdressMap/qqmap-wx-jssdk.js');
var util = require('../../utils/util.js');
let qqmapsdk;
Page({
  data: {
    disabled: false,
    carContent: "三轮车只服务当地城区内，停车费和搬运费，请用户额外支付若涉及逾时等候费，请与司机按收费标准结算",
    carmessage: "请用户在司机到达前完成物品打包，现金等贵重物品请妥善保管",
    showtab: 0,
    imgClick: 0,
    textColor1: color,
    textColor2: defaultColor,
    textColor3: defaultColor,
    price: 0.00,
    startPrice: 0.00,
    imgUrl: "../images/select.png",
    up_adress: {
      sAddress: '添加信息',
      code: "",
      sPerson: "添加信息"
    },
    down_adress: {
      sAddress: '添加信息',
      code: "",
      sPerson: "添加信息"
    },
    tabnav: {
      tabnum: 3,
      tabitem: [{
          "id": 0,
          "vehicleName": "三轮车",
          "imgUrl": "www.ebbtcps.com:9090/images/sanlun.jpg",
          "agentId": "",
          "vehicleModle": "",
          "vehicleId": "",
          "startPrice": 0.00,
          "carContent": "三轮车只服务当地城区内，停车费和搬运费，请用户额外支付若涉及逾时等候费，请与司机按收费标准结算",
          "carmessage": "请用户在司机到达前完成物品打包，现金等贵重物品请妥善保管",
          "weight": "210",
          "distance":5

        },
        {
          "id": 1,
          "vehicleName": "面包车",
          "imgUrl": "www.ebbtcps.com:9090/images/mianbao.jpg",
          "agentId": "",
          "vehicleModle": "",
          "vehicleId": "",
          "startPrice": 0.00,
          "carContent": "若产生高速费，停车费和搬运费，请用户额外支付若涉及逾时等候费，请与司机按收费标准结算",
          "carmessage": "请用户在司机到达前完成物品打包，现金等贵重物品请妥善保管",
          "weight": "800",
          "distance": 5
        },
        {
          "id": 2,
          "vehicleName": "厢式货车",
          "imgUrl": "www.ebbtcps.com:9090/images/huoche.jpg",
          "agentId": "",
          "vehicleModle": "",
          "vehicleId": "",
          "startPrice": 0.00,
          "carContent": "若产生高速费，停车费和搬运费，请用户额外支付若涉及逾时等候费，请与司机按收费标准结算",
          "carmessage": "请用户在司机到达前完成物品打包，现金等贵重物品请妥善保管",
          "weight": "1000",
          "distance": 5
        },
      ]
    },
    vehicleList: [],
    phone: "",
    code: "",
    timer: '', //定时器名字
    countDownNum: '获取验证码',
    pelepeNum: "",
    remark: "",
    distance: "",
    numInput: "",
    remarkInput: "",
    cityCode: "",
    peopleNums: "请选择需要几个工人",
    isShow: true,
    peopleList: [
      '不需要', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    ]
    //textTitle:"获取验证码"
  },
  onLoad: function() {
    qqmapsdk = new QQMapWX({
      key: 'BKKBZ-YQR6F-H2EJG-JCXFA-LEPTF-SVB2J'
    });
    this.getCityCode();
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  onShow: function() {
    var that = this;
    console.log(that.data.up_adress)
    // if (that.data.down_adress.sAddress != "添加信息" && that.data.up_adress.sAddress != "添加信息") {
    //   that.getVehicle_info()
    // }
    if (that.data.down_adress.sAddress != "添加信息" && that.data.up_adress.sAddress != "添加信息") {
      console.log(that.data.up_adress)
      that.getDistance(that.data.up_adress.sLocation, that.data.down_adress.sLocation)
    }
  },
  //获取城市代码 
  getCityCode: function() {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {
        console.log(res.latitude, res.longitude)
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function(res) {
            that.getCarInfo(res.result.ad_info.adcode)
          },
          fail: function(res) {
            console.log(res);
          },
          complete: function(res) {
            // console.log(res);
          }
        })
      },
    })
  },
  //计算两点之间的距离
  getDistance: function(fromAdress, toAdress) {
    var that = this;
    qqmapsdk.calculateDistance({
      mode: 'driving', //可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
      //from参数不填默认当前地址
      from: fromAdress || '', //若起点有数据则采用起点坐标，若为空默认当前地址
      to: toAdress, //终点坐标
      success: function(res) {
        console.log(res);
        var res = res.result;
        var index = that.data.showtab;
        var agentId = that.data.tabnav.tabitem[index].agentId;
        var vehicleId = that.data.tabnav.tabitem[index].vehicleId;
        var distance = res.elements[0].distance;

        that.setData({
          distance: distance
        })
        //获取运费
        that.getPrice(agentId, vehicleId, distance)
      },
      fail: function(error) {
        console.error(error);
      },
      complete: function(res) {
        console.log(res);
      }
    });
  },
  //获取本地代理商
  getVehicle_info: function(e) {
    const that = this;
    if (that.data.up_adress.code != "") {
      wx.request({
        url: getApp().globalData.requestURL + '/api/vehicle/get',
        data: {
          code: that.data.up_adress.code
        },
        method: 'GET',
        header: {
          "content-type": "application/json"
        },
        success: function(res) {
          console.log("车量信息")
          console.log(res.data.result)
          if (res.data.result.length == 0) {
            wx.showModal({
              title: '提示',
              content: '当前地区没有代理商，无法提交订单',
              showCancel: false,
              success(res) {
                that.setData({
                  disabled: true
                })
              }
            })
          } else {
            //that.getPrice();//获取运费价格
            that.setData({
              vehicleList: res.data.result
            })
          }

        },
        fail: function(err) {
          console.log(err.errMsg)
        }

      })
    }


  },
  //获取运费价格
  getPrice: function(agemtId, carType, distance) {
    var that = this;
    wx.request({
      url: getApp().globalData.requestURL + '/api/price/calculation',
      data: {
        agentId: agemtId,
        carType: carType,
        distance: distance
      },
      method: 'POST',
      header: {
        "content-type": "application/json"
      },
      success: function(res) {
        that.setData({
          price: res.data
        })
      }
    })
  },
  //获取取货地址
  getUp_adress: function(e) {
    wx.navigateTo({
      url: '../adress/adress?type=1',
    })
  },
  //获取收货地址
  getDown_adress: function(e) {
    wx.navigateTo({
      url: '../adress/adress?type=2',
    })
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  setTab: function(e) {
    var that = this;
    //var agemtId = that.data.tabnav.tabitem[edata.tabindex].agentId
    var edata = e.currentTarget.dataset;
    //console.log(edata.tabindex)
    if (edata.tabindex == 1) {
      that.setData({
        showtab: edata.tabindex,
        textColor1: defaultColor,
        textColor2: color,
        textColor3: defaultColor,
        startPrice: that.data.tabnav.tabitem[edata.tabindex].startPrice
      })
    } else if (edata.tabindex == 2) {
      that.setData({
        showtab: edata.tabindex,
        textColor1: defaultColor,
        textColor2: defaultColor,
        textColor3: color,
        startPrice: that.data.tabnav.tabitem[edata.tabindex].startPrice
      })
    } else {
      that.setData({
        showtab: edata.tabindex,
        textColor1: color,
        textColor2: defaultColor,
        textColor3: defaultColor,
        startPrice: that.data.tabnav.tabitem[edata.tabindex].startPrice
      })
    }
    if (that.data.down_adress.sAddress != "添加信息" && that.data.up_adress.sAddress != "添加信息") {
      console.log(that.data.up_adress)
      that.getDistance(that.data.up_adress.sLocation, that.data.down_adress.sLocation)
    }
  },
  //汽车说明弹窗
  getQuestion: function(e) {
    //console.log("关于汽车说明")
    this.setData({
      modalHidden: true,
      ifName: true,
    });

  },
  //是否需要工人
  imgChange: function(e) {
    var that = this;
    var times = e.currentTarget.dataset.id
    if (times == 0) {
      console.log("选中")
      that.setData({
        imgClick: 1,
        imgUrl: "../images/selected.png",
      })
    } else {
      console.log("未选中")
      that.setData({
        imgClick: 0,
        imgUrl: "../images/select.png",
      })
    }

  },
  //需要工人的数量
  getPelepeNum: function(e) {
    var that = this;
    that.setData({
      pelepeNum: e.detail.value
    })
  },
  //备注
  getRemark: function(e) {
    var that = this;
    that.setData({
      remark: e.detail.value
    })
  },
  //提交订单
  putOrder: function(e) {
    var that = this;
    console.log("提交订单")
    const user = wx.getStorageSync("we_userInfo");
    if (user.user.phone == "0") {
      this.setData({
        modalHidden: true,
        ifNameYou: true,
      });
    } else {
      //console.log(that.data.vehicleList)
      if (that.data.down_adress.sAddress == "添加信息" || that.data.up_adress.sAddress == "添加信息") {
        wx.showModal({
          title: '提交订单失败',
          content: '请填写取货/收货信息',
          showCancel: false,
          success(res) {}
        })
      } else {
        var index = that.data.showtab;
        var fromAdress = that.data.up_adress;
        var toAdress = that.data.down_adress;
        var isUpPop = that.data.imgClick;
        var nums = that.data.pelepeNum;
        var remark = that.data.remark;
        var price = that.data.price + that.data.startPrice;
        var distance = that.data.tabnav.tabitem[index].distance;
        var agentId = that.data.tabnav.tabitem[index].agentId;
        var vehicleId = that.data.tabnav.tabitem[index].vehicleId;
        var time = util.formatTime(new Date());
        var carname = that.data.tabnav.tabitem[index].vehicleName;

        var info = JSON.stringify({
          userId: user.user.userId,
          agentId: agentId,
          openId: user.user.openId,
          carType: vehicleId,
          saddress: fromAdress.sAddress,
          slocation: fromAdress.sLocation,
          sperson: fromAdress.sPerson,
          sphone: fromAdress.sPhone,
          eaddress: toAdress.sAddress,
          elocation: toAdress.sLocation,
          eperson: toAdress.sPerson,
          ephone: toAdress.sPhone,
          isupdown: isUpPop,
          personcount: nums,
          distance: distance,
          remark: remark,
          downtime: time,
          carName: carname
        })
        console.log(JSON.parse(info))

        if (toAdress.sPerson) {
          //提交统一支付
          wx.request({
            url: getApp().globalData.requestURL + '/api/order/add',
            data: {
              userId: user.user.userId,
              agentId: agentId,
              openId: user.user.openId,
              carType: vehicleId,
              saddress: fromAdress.sAddress,
              slocation: fromAdress.sLocation,
              sperson: fromAdress.sPerson,
              sphone: fromAdress.sPhone,
              eaddress: toAdress.sAddress,
              elocation: toAdress.sLocation,
              eperson: toAdress.sPerson,
              ephone: toAdress.sPhone,
              isupdown: isUpPop,
              personcount: nums,
              distance: distance,
              remark: remark,
              downtime: time,
              carName: carname
            },
            method: 'POST',
            header: {
              "content-type": "application/json"
            },
            success: function(res) {
              console.log(res.data)
              var payInfo = res.data.result;
              if (payInfo.code == "SUCCESS") {
                wx.navigateTo({
                  url: '../pay/pay?info=' + JSON.stringify(payInfo) + '&price=' + price,
                })
              } else {
                wx.showModal({
                  title: '提交订单失败',
                  content: payInfo.msg,
                  showCancel: false,
                  success(res) {}
                })
              }

            },
            fail: function(err) {
              console.log(err.errMsg)
            }

          })
        } else {
          wx.showModal({
            title: '提交订单失败',
            content: '请添加收获信息',
            showCancel: false,
            success(res) {}
          })
        }

      }
    }
  },
  setValueCode: function(e) {
    //console.log(e.detail.value)
    var that = this;
    that.setData({
      code: e.detail.value
    });

  },
  setValuePhone: function(e) {
    //console.log(e)
    var that = this;
    that.setData({
      phone: e.detail.value
    });

  },
  //获取验证码
  getCode: function(e) {
    //console.log("获取验证码")
    const that = this;
    if (that.data.phone != "") {
      wx.request({
        url: getApp().globalData.requestURL + '/api/phone/getCode',
        data: {
          phone: that.data.phone
        },
        method: 'GET',
        success: function(res) {
          //console.log(res)
          if (res.data.result) {
            that.countDown();
          } else {
            wx.showModal({
              title: '提示',
              content: '获取验证码失败，请重新获取',
              showCancel: false,
              success(res) {}
            })
          }

        },
        fail: function(err) {
          console.log(err.errMsg)
        }

      })
    }
  },
  //手机号信息验证提交
  confirm: function() {
    var that = this;
    const user = wx.getStorageSync("we_userInfo");
    //console.log(that.data.code)

    if (user) {
      wx.request({
        url: getApp().globalData.requestURL + '/api/phone/login',
        data: {
          code: that.data.code,
          phone: that.data.phone,
          userId: user.user.userId
        },
        header: {
          "content-type": "application/json"
        },
        method: 'POST',
        success: function(res) {
          console.log(res.data)
          if (res.data.result.code != "ERROR") {
            that.setData({
              modalHidden: false,
              ifNameYou: false,
            });
            try {
              wx.setStorageSync('we_userInfo', res.data.result)
            } catch (e) {
              console.log('we_userinfo存储失败' + e)
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.result.msg,
              showCancel: false,
              success(res) {}
            })
          }

        },
        fail: function(err) {
          console.log(err.errMsg)
        }
      })
    }

  },
  //弹出框无输入
  cancel: function() {
    this.setData({
      modalHidden: false,
      ifName: false,
    });
  },
  cancelYou: function() {
    this.setData({
      modalHidden: false,
      ifNameYou: false,
    });
  },
  //计时器
  countDown: function() {
    let that = this;
    let countDownNum = 60; //获取倒计时初始值
    //如果将定时器设置在外面，那么用户就看不到countDownNum的数值动态变化，所以要把定时器存进data里面
    that.setData({
      timer: setInterval(function() { //这里把setInterval赋值给变量名为timer的变量
        //每隔一秒countDownNum就减一，实现同步
        countDownNum--;
        //然后把countDownNum存进data，好让用户知道时间在倒计着
        that.setData({
          countDownNum: countDownNum
        })
        //在倒计时还未到0时，这中间可以做其他的事情，按项目需求来
        if (countDownNum == 0) {
          //这里特别要注意，计时器是始终一直在走的，如果你的时间为0，那么就要关掉定时器！不然相当耗性能
          //因为timer是存在data里面的，所以在关掉时，也要在data里取出后再关闭
          clearInterval(that.data.timer);
          //关闭定时器之后，可作其他处理codes go here
          that.setData({
            countDownNum: "获取验证码"
          })
        }
      }, 1000)
    })
  },
  //获取车量配置信息
  getCarInfo: function(code) {
    const that = this;
    if (code != "") {
      wx.request({
        url: getApp().globalData.requestURL + '/api/vehicle/getVehiclesByAgentId',
        data: {
          code: code
        },
        method: 'GET',
        success: function(res) {
          console.log("代理商车辆信息")
          console.log(res)
          var carList = res.data.result;
          if (res.data.result.length != 0) {
            that.setData({
              tabnav: {
                tabnum: carList.length,
                tabitem: [{
                    "id": 0,
                    "vehicleName": carList[0].vehicleName,
                    "imgUrl": carList[0].imgPath,
                    "agentId": carList[0].agentId,
                    "vehicleModle": carList[0].vehicleModle,
                    "vehicleId": carList[0].vehicleId,
                    "startPrice": carList[0].startPrice,
                    "distance": carList[0].distance,
                  "carContent": "三轮车只服务当地城区内，停车费和搬运费，请用户额外支付若涉及逾时等候费，请与司机按收费标准结算",
                  "carmessage": "请用户在司机到达前完成物品打包，现金等贵重物品请妥善保管",
                  "weight": "210",
                  },
                  {
                    "id": 1,
                    "vehicleName": carList[1].vehicleName,
                    "imgUrl": carList[1].imgPath,
                    "agentId": carList[1].agentId,
                    "vehicleModle": carList[1].vehicleModle,
                    "vehicleId": carList[1].vehicleId,
                    "startPrice": carList[1].startPrice,
                    "distance": carList[1].distance,
                    "carContent": "若产生高速费，停车费和搬运费，请用户额外支付若涉及逾时等候费，请与司机按收费标准结算",
                    "carmessage": "请用户在司机到达前完成物品打包，现金等贵重物品请妥善保管",
                    "weight": "800"
                  },
                  {
                    "id": 2,
                    "vehicleName": carList[2].vehicleName,
                    "imgUrl": carList[2].imgPath,
                    "agentId": carList[2].agentId,
                    "vehicleModle": carList[2].vehicleModle,
                    "vehicleId": carList[2].vehicleId,
                    "startPrice": carList[2].startPrice,
                    "distance": carList[2].distance,
                    "carContent": "若产生高速费，停车费和搬运费，请用户额外支付若涉及逾时等候费，请与司机按收费标准结算",
                    "carmessage": "请用户在司机到达前完成物品打包，现金等贵重物品请妥善保管",
                    "weight": "1000"
                  },
                ]
              },
              startPrice: carList[0].startPrice
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '抱歉，当前位置没有服务商',
              showCancel: false,
              success(res) {}
            })
          }

        },
        fail: function(err) {
          console.log(err.errMsg)
        }

      })
    }
  },
  changImage: function(e) {
    // console.log(e)
    var that = this;
    var changId = e.currentTarget.dataset.id
    console.log(that.data.showtab)
    if (changId == 0) {
      //左滑
      if (that.data.showtab == 1) {
        that.setData({
          showtab: 0,
          textColor1: color,
          textColor2: defaultColor,
          textColor3: defaultColor,
          startPrice: that.data.tabnav.tabitem[0].startPrice
        })
      } else if (that.data.showtab == 2) {
        that.setData({
          showtab: 1,
          textColor1: defaultColor,
          textColor2: color,
          textColor3: defaultColor,
          startPrice: that.data.tabnav.tabitem[1].startPrice
        })
      } else {
        that.setData({
          showtab: 0,
          textColor1: color,
          textColor2: defaultColor,
          textColor3: defaultColor,
          startPrice: that.data.tabnav.tabitem[0].startPrice
        })
      }
    } else {
      //右滑
      if (that.data.showtab == 1) {
        that.setData({
          showtab: 2,
          textColor1: defaultColor,
          textColor2: defaultColor,
          textColor3: color,
          startPrice: that.data.tabnav.tabitem[2].startPrice
        })
      } else if (that.data.showtab == 2) {
        that.setData({
          showtab: 2,
          textColor1: defaultColor,
          textColor2: defaultColor,
          textColor3: color,
          startPrice: that.data.tabnav.tabitem[2].startPrice
        })
      } else {
        that.setData({
          showtab: 1,
          textColor1: defaultColor,
          textColor2: color,
          textColor3: defaultColor,
          startPrice: that.data.tabnav.tabitem[1].startPrice
        })
      }
    }
    if (that.data.down_adress.sAddress != "添加信息" && that.data.up_adress.sAddress != "添加信息") {
      console.log(that.data.up_adress)
      that.getDistance(that.data.up_adress.sLocation, that.data.down_adress.sLocation)
    }
  },
  getPeopleNumbers: function(e) {
    var that = this;
    that.setData({
      isShow: false,
      modalHidden: true,
      value: [0],
      peopleNums: "不需要人"
    })
  },
  bindChange: function(e) {
    const val = e.detail.value;
    var that = this;
    console.log(val)
    var value = that.data.peopleList[val] + "人";
    var num = that.data.peopleList[val];
    var imgClick = 1;
    if (val == 0) {
      num = 0;
      imgClick = 0;
    }
    console.log(value);
    that.setData({
      peopleNums: value,
      pelepeNum: num,
      imgClick: imgClick
    })
  },
  people_click: function(e) {
    var id = e.currentTarget.dataset.id;
    var that = this;
    if (id == 1) {
      //取消
      that.setData({
        isShow: true,
        modalHidden: false,
        peopleNums: "请选择需要几个工人",
      })
    } else {
      //确定
      var imgClick;
      that.setData({
        isShow: true,
        modalHidden: false
      })
    }
  }
})